package xyz.heyaoshare.utils;

import cn.hutool.http.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * IP工具类
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午10:46
 */
@Slf4j
public class IPUtils {

    /**
     * 获取客户端的IP地址。
     *
     * @param request HttpServletRequest对象
     * @return 客户端的IP地址，如果无法获取到客户端的IP地址，则返回"unknown"
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
    }

    /**
     * 判断给定的IP地址是否为内网IP地址或本地回环地址
     *
     * @param ip 要判断的IP地址
     * @return 如果给定的IP地址是内网IP地址或本地回环地址，则返回true；否则返回false
     */
    public static boolean internalIp(String ip) {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr) || "127.0.0.1".equals(ip);
    }

    /**
     * 判断给定的IP地址是否为内部IP地址。
     *
     * @param addr 一个字节数组，表示IP地址
     * @return 如果给定的IP地址是内部IP地址，则返回true；否则返回false
     */
    private static boolean internalIp(byte[] addr) {
        if (addr == null || addr.length < 2) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        // 172.16.x.x/12
        final byte SECTION_2 = (byte) 0xAC;
        final byte SECTION_3 = (byte) 0x10;
        final byte SECTION_4 = (byte) 0x1F;
        // 192.168.x.x/16
        final byte SECTION_5 = (byte) 0xC0;
        final byte SECTION_6 = (byte) 0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                if (b1 == SECTION_6) {
                    return true;
                }
            default:
                return false;
        }
    }

    /**
     * 将文本转换为数值格式版本4
     *
     * @param text 要转换的文本字符串
     * @return 转换后的字节数组，如果文本为空或格式错误则返回null
     */
    public static byte[] textToNumericFormatV4(String text) {
        if (text.isEmpty()) {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return null;
                    }
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return null;
                    }
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return bytes;
    }

    /**
     * 获取本地主机的IP地址。
     *
     * @return 返回本地主机的IP地址，如果获取失败则返回 "127.0.0.1"。
     */
    public static String getHostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignored) {

        }
        return "127.0.0.1";
    }

    /**
     * 获取当前主机名
     *
     * @return 当前主机名，如果获取失败则返回 "未知"
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ignored) {

        }
        return "未知";
    }

    /**
     * 获取多级反向代理的 IP 地址
     *
     * @param ip 原始 IP 地址，可能包含多个 IP 地址，用逗号分隔
     * @return 第一个非 "unknown" 的 IP 地址，如果全是 "unknown" 则返回原 IP 地址
     */
    public static String getMultistageReverseProxyIp(String ip) {
        // 反向代理检测
        if (ip.indexOf(",") > 0) {
            final String[] ips = ip.trim().split(",");
            for (String sub : ips) {
                if (!"unknown".equalsIgnoreCase(sub)) {
                    ip = sub;
                    break;
                }
            }
        }
        return ip;
    }


    // 实时查询
    public static final String ADDRESS_URL = "https://whois.pconline.com.cn/ipJson.jsp";
    public static final String UNKNOWN = "未知";

    /**
     * 根据IP地址获取其地理位置信息
     *
     * @param ip 要查询的IP地址
     * @return 返回对应的地理位置信息，如果IP为内网IP则返回"内网IP"，如果获取失败则返回UNKNOWN
     */
    public static String getAddress(String ip) {
        // 内网
        if (internalIp(ip)) {
            return "内网IP";
        }

        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("ip", ip);
            paramMap.put("json", true);
            String response = HttpUtil.get(ADDRESS_URL, paramMap);
            if (StrUtils.isBlank(response)) {
                log.error("根据IP：{} 获取地址web服务返回空！", ip);
                return UNKNOWN;
            }

            Address address = JSONUtils.parseObject(response, Address.class);
            assert address != null;
            return String.format("%s %s", address.getPro(), address.getCity());
        } catch (Exception e) {
            log.error("根据IP：{} 获取地址异常！", ip);
        }

        return UNKNOWN;
    }

    /**
     * 根据客户端的IP地址获取其地理位置信息。
     *
     * @param request HttpServletRequest对象，包含了客户端的请求信息
     * @return 客户端的地理位置信息，如果获取失败则返回null
     */
    public static String getAddressByIP(HttpServletRequest request) {
        return getAddress(getIpAddr(request));
    }

    @Data
    static class Address {
        /**
         * 省
         */
        private String pro;
        /**
         * 市
         */
        private String city;
    }

}